<!-- src/components/MusicView.vue -->
<template>
  <v-app>
    <v-container>
      <v-row>
        <v-col cols="12">
          <v-card>
            <v-card-title>
              音色管理
              <v-spacer></v-spacer>
              <v-btn color="primary" @click="openDialog()">
                添加音色
              </v-btn>
            </v-card-title>
            <v-card-text>
              <v-text-field
                  v-model="search"
                  label="搜索音色"
                  class="mb-4"
                  clearable
              ></v-text-field>
              <!--    <v-select-->
              <!--        v-model="search_package_id"-->
              <!--        :items="music_packages"-->
              <!--        label="请根据音乐包所有对应的音乐"-->
              <!--        item-title="name"-->
              <!--        item-value="id"-->
              <!--        variant="outlined"-->
              <!--        @update:modelValue="handleSelectChange"-->
              <!--    ></v-select>-->
              <v-data-table
                  :headers="headers"
                  :items="voices"
                  :loading="loading"
                  :search="search"
                  class="elevation-1"
              >
                <template v-slot:item.actions="{ item }">
                  <v-icon small @click="openEditDialog(item)">
                    mdi-pencil
                  </v-icon>

                  <v-icon small @click="deleteItem(item)">
                    mdi-delete
                  </v-icon>
                </template>
              </v-data-table>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>

      <!-- 编辑对话框 -->
      <v-dialog v-model="dialog" max-width="500px">
        <v-card>
          <v-card-title>
            <span>{{ formTitle }}</span>
          </v-card-title>
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12">
                  <v-text-field
                      v-model="editedItem.name"
                      label="音色名称"
                  ></v-text-field>
                </v-col>
                <v-col cols="12">
                  <v-text-field
                      v-model="editedItem.workflow_id"
                      label="音色workflowID"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-container>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="close">取消</v-btn>
            <v-btn color="blue darken-1" text @click="save">保存</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

      <!-- 删除确认对话框 -->
      <v-dialog v-model="dialogDelete" max-width="500px">
        <v-card>
          <v-card-title>确认删除</v-card-title>
          <v-card-text>确定要删除这条音乐记录吗？</v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="closeDelete">取消</v-btn>
            <v-btn color="blue darken-1" text @click="deleteItemConfirm">确认</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-container>
  </v-app>
</template>

<script>
const API_BASE = import.meta.env.VITE_API_BASE || 'http://106.75.215.61:3000';

export default {
  name: 'MusicView',
  data: () => ({
    apiBase: API_BASE,
    dialog: false,
    dialogDelete: false,
    loading: false,
    search: '', // 搜索关键词
    // ✅ 改为 Vuetify 3 的写法：title + key
    headers: [
      { title: '音色ID', key: 'id' },
      { title: '音色名称', key: 'name' },
      { title: '音色workflow_id', key: 'workflow_id' },
      { title: '操作', key: 'actions', sortable: false }
    ],
    voices: [],
    music_packages: [],
    search_package_id: "全部",
    editedIndex: -1,
    editedItem: {
      id: '',
      name: '',
      workflow_id: '',
      file: null
    },
    defaultItem: {
      id: '',
      name: '',
      workflow_id: '',
      file: null
    }
  }),

  computed: {
    formTitle() {
      return this.editedIndex === -1 ? '新增音色' : '编辑音色'
    },
  },

  methods: {
    async getAllVoices() {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/voiceList`)
        this.voices = res?.data?.data;
        console.log(this.voices)
      } catch (e) {
        this.$toast?.error('获取音色列表失败')
      } finally {
        this.loading = false
      }
    },
    async deleteMusic(id) {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/deleteVoice/` + id)
        if (res.status === 200) {
          this.$toast?.success('删除成功')
        } else {
          throw new Error('删除失败')
        }
      } catch (e) {
        this.$toast?.error('删除失败')
      } finally {
        this.loading = false
      }
    },

    async handleSelectChange(){
      console.log('选中的值:', this.search_package_id);
    },

    openDialog() {
      this.editedIndex = -1
      this.editedItem = Object.assign({}, this.defaultItem)
      this.dialog = true
    },

    openEditDialog(item) {
      this.editedIndex = this.voices.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.dialog = true
    },

    deleteItem(item) {
      this.editedIndex = this.voices.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.dialogDelete = true
    },

    close() {
      this.dialog = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    closeDelete() {
      this.dialogDelete = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    async save() {
      if (!this.editedItem.name || !this.editedItem.workflow_id) {
        this.$toast?.error('模板名称和workflow_id不能为空')
        return
      }

      if (this.editedIndex > -1) {//编辑
        this.loading = true
        try {
          const response = await this.$axios.post(`${this.apiBase}/updateVoice`, {
            id: this.editedItem.id,
            name: this.editedItem.name,
            workflow_id: this.editedItem.workflow_id,
          })
          if (response.status !== 200) throw new Error('更新失败')
          this.$toast?.success('更新成功')
          Object.assign(this.voices[this.editedIndex], this.editedItem)
          await this.getAllVoices()
          // console.log('1111111')
          this.close()
        } catch (e) {
          this.$toast?.error('更新失败')
        } finally {
          this.loading = false
        }
      } else {//新增
        this.loading = true
        try {
          const response = await this.$axios.post(`${this.apiBase}/addVoice`, {
            name: this.editedItem.name,
            workflow_id: this.editedItem.workflow_id,
          })

          console.log(response)
          if (response.status !== 200) throw new Error('创建失败')
          const { id, name, workflow_id } = response.data.data
          // console.log('22222')
          Object.assign(this.editedItem, { id, name, workflow_id })
          this.$toast?.success('创建成功')
          this.voices.push(this.editedItem)
          await this.getAllVoices()
          this.close()
        } catch (e) {
          this.$toast?.error('更新失败')
        } finally {
          this.loading = false
        }
      }

      this.close()
    },

    async deleteItemConfirm() {
      await this.deleteMusic(this.editedItem.id)
      this.voices.splice(this.editedIndex, 1)
      this.closeDelete()
      await this.getAllVoices()
    }
  },

  mounted() {
    this.getAllVoices()
  }
}
</script>
